﻿using ImageManager.Common;
using ImageManager.DBAccess;
using ImageManager.Model;

namespace ImageManager.ImageService
{
    public class ImageServiceProvider : BaseServiceProvider<ImageModel>
    {
        public List<ImageModel> ListMyDownload(CondCollection cond,string startDate,string endDate, int index, int pageSize, out int total)
        {
            var user = ServiceLoader.GetService<OnlineUser>();
            var dwsql = String.Format("PK IN (SELECT IMAGE FROM T_DOWNLOADHISTORY WHERE DEL = 'N' AND CREATEDATE >= '{0}' AND CREATEDATE <= '{1}' AND CREATOR = '{2}')",
               startDate, endDate, user.UserId);
            return qryInstance.Where(cond).Where(dwsql).ToPageList(pageSize, index, out total);
        }
        public override void Save(ImageModel data)
        {
            if (String.IsNullOrWhiteSpace(data.Author))
            {
                var user = ServiceLoader.GetService<OnlineUser>();
                data.Author = user.UserName;
            }
            if (String.IsNullOrWhiteSpace(data.SeriesName) && !String.IsNullOrWhiteSpace(data.Series))
            { 
                var seriesSP = ServiceLoader.GetService<SeriesServiceProvider>();
                var s = seriesSP.Get(data.Series);
                data.SeriesName = s.SeriesName;
            }
            base.Save(data);
        }
        public ImageModel CreateByImage(Stream stream,bool video)
        {
            int MAX_PREVIEW = int.Parse(ConfigReader.ReadSetting("Image", "PreviewMax"));
            int MAX_THUM = int.Parse(ConfigReader.ReadSetting("Image", "ThumMax"));
            var text = ConfigReader.ReadSetting("Image", "Watermark");
            stream.Seek(0, SeekOrigin.Begin);
            var imageCode = ImageTools.CreateImageCode();
            var orgiImgCode = Utils.MakeRandom();
            var date = DateTime.Today.ToString("yyyyMMdd");
            var paths = ImageTools.GetPath(date);
            if (!video)
            {
                using (var previewStream = ImageTools.Compress(stream, MAX_PREVIEW, 80))
                {
                    var st = ImageTools.Watermark(previewStream, text);
                    using (var previewFs = File.OpenWrite(paths[2] + "/" + imageCode + ".jpg"))
                    {
                        st.CopyTo(previewFs);
                        previewFs.Flush();
                    }
                }
                using (var thumbnailStream = ImageTools.Compress(stream, MAX_THUM, 80))
                {
                    using (var thumbnailFs = File.OpenWrite(paths[3] + "/" + imageCode + ".jpg"))
                    {
                        thumbnailStream.CopyTo(thumbnailFs);
                        thumbnailFs.Flush();
                    }
                }
            }
            using (var streamFs = File.OpenWrite(paths[1] + "/" + orgiImgCode))
            {
                stream.Seek(0, SeekOrigin.Begin);
                stream.CopyTo(streamFs);
                streamFs.Flush();
            }
            var imageModel = new ImageModel()
            {
                ImageCode = imageCode,
                OrigImgPath = orgiImgCode,
                DayPath = date
            };
            return imageModel;
        }
        public void UpdateHeat(string pk)
        {
            var sql = String.Format("update t_image set heat = (select count(*) from t_downloadhistory  where del = 'N' and t_downloadhistory.image=t_image.pk) where pk = '{0}'", pk);
            udpInstance.DoExec(sql);
        }
        public Stream Download(ImageModel model)
        {
            var paths = ImageTools.GetPath(model.DayPath);
            var fs = File.OpenRead(paths[1] + "/" + model.OrigImgPath);
            return fs;
        }
        public Stream Thumbnail(ImageModel model)
        {
            var paths = ImageTools.GetPath(model.DayPath);
            var fs = File.OpenRead(paths[3] + "/" + model.ImageCode + ".jpg");
            return fs;
        }
        public Stream Preview(ImageModel model)
        {
            var paths = ImageTools.GetPath(model.DayPath);
            var fs = File.OpenRead(paths[2] + "/" + model.ImageCode+".jpg");
            return fs;
        }

        public Stream ToExcel(string period)
        {
            string sqlstr = "SELECT A.IMAGENAME 文件名,A.CREATEDATE 上传日期,A.SERIESNAME 系列名,B.USERNAME 上传人,A.PRICE 上传点数 FROM T_IMAGE A LEFT JOIN T_USER B ON A.CREATOR = B.PK WHERE A.CREATEDATE LIKE @P";
            return Utils.ToExcelStream(qryInstance.ToTable(sqlstr,period+"%"));
        }
    }
}
